"""
move_to_element(element)：鼠标悬停
必须调用 .perform() 才能执行动作
"""
from time import sleep

from selenium import webdriver
from selenium.common import NoSuchElementException
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait


def find_element(driver, by, value) -> WebElement:
    try:
        element = driver.find_element(by, value)
        return element
    except Exception as e:
        return None


driver = webdriver.Edge()
driver.get("http://www.zlcode.top")

# 隐式等待：后续所有的 find_element 操作都会最多等待 10 秒
driver.implicitly_wait(10)

driver.maximize_window()

net_set = find_element(driver, By.CSS_SELECTOR, "#app > div > div.first > div > div:nth-child(4) > div > div > button")

if net_set:
    net_set.click()

login_img = find_element(driver, By.XPATH, "/html/body/div[1]/div/div/div[1]/div/div/div[2]/div[2]/div[4]/span/img")

if login_img:
    # move_to_element(element)：鼠标悬停
    actions = ActionChains(driver)
    actions.move_to_element(login_img).perform()  # 必须调用 .perform() 才能执行动作

go_login = find_element(driver, By.CSS_SELECTOR, "body > div.arco-trigger-popup.arco-trigger-position-bottom.arco-popover > div > div.arco-trigger-content.arco-popover-popup-content > div.arco-popover-content > div > div.el-card.is-hover-shadow")

if go_login:
    go_login.click()

user_name = find_element(driver, By.XPATH, "/html/body/div[1]/div/div/div[2]/form/div[1]/div[2]/div/div/input")
password = find_element(driver, By.XPATH, "/html/body/div[1]/div/div/div[2]/form/div[2]/div[2]/div/div/input")
rectify_code = find_element(driver, By.XPATH, "/html/body/div[1]/div/div/div[2]/form/div[3]/div[2]/div[1]/div/input")
login_button = find_element(driver, By.CSS_SELECTOR, "#app > div > div > div.el-col.el-col-12.right > form > div:nth-child(4) > div.el-form-item__content > button > span")

if user_name and password and rectify_code and login_button:
    user_name.send_keys("zlcode123")  # 正确的账号
    password.send_keys("zlcode123456")  # 正确的密码
    rectify_code.send_keys("123")  # 错误的验证码
    login_button.click()


notify = WebDriverWait(driver,3).until(
    expected_conditions.presence_of_element_located((By.XPATH, "/html/body/div[3]/p/el-row/el-row[1]"))
)
print(notify.get_attribute("textContent"))
